import { createStore } from 'vuex';

const vuexLocalStorage = (store) => {
    // 当store初始化时，从localStorage中恢复状态
    if (localStorage.getItem("shopping_list")) {
        store.replaceState({
            ...store.state,
            shopping_list: JSON.parse(localStorage.getItem("shopping_list"))
        });
    }
    // 监听每次mutation的触发，在mutation完成后将状态保存到localStorage中
    store.subscribe((mutation, state) => {
        localStorage.setItem("shopping_list", JSON.stringify(state.shopping_list));
    });
};

const store = createStore({
    state() {
        return {
            count: 0,
        //    购物车的数量
            shopping_num:99,
            //主页广告栏的图片
            Maid_picture_list:[
                {id:1,src:'https://k.sinaimg.cn/n/sinakd20230922s/612/w621h791/20230922/6633-57c796413f2e18b5490058929b3fa4b0.png/w700d1q75cms.jpg?by=cms_fixed_width'},
                {id:1,src:'http://img.moehot.com/img/2024/05/30/0001/4PHHF995K1JGGNNHCAP0R6AAD.jpg'},
                {id:1,src:'https://ts1.cn.mm.bing.net/th/id/R-C.6561259a797b804be9be644d909a517d?rik=8%2bAYEsO10DSPwA&riu=http%3a%2f%2fseopic.699pic.com%2fphoto%2f40015%2f4907.jpg_wh1200.jpg&ehk=Qx1SdhPWfJjLn8O2Xaxn%2b8yWdydwk57brbfhJUjAXk4%3d&risl=&pid=ImgRaw&r=0'}
            ],
            goodLists1:[
                {goods_id:1,goods_name:'《时光代理人》动画-Leisure time系列流沙票根-李天辰&李天希款',goods_price:35,goods_big_logo:'http://img.moehot.com/img/2024/06/11/0008/04M4EZXBCE69TFHTCAQ5M0K6Z.jpg_400x400'},
                {goods_id:1,goods_name:'代理版 明日方舟 景品手办 阿米娅 泳装 VER.',goods_price:145,goods_big_logo:'http://img.moehot.com/img/2023/07/14/0005/03R87TTB4K3JRKDCB9PRE0E66.jpg_400x400'},
                {goods_id:1,goods_name:'Huggy Good Smile 贴贴 蓝色监狱 凪诚士郎 可动模型',goods_price:107,goods_big_logo:'http://img.moehot.com/img/2024/05/20/0010/S6507EG3HAYNG3EPCAN14NQJ0.jpg'},
                {goods_id:1,goods_name:'JP 排球少年!! 拍立得收藏卡第7弹（盒装12个入）',goods_price:480,goods_big_logo:'http://img.moehot.com/img/2024/06/11/0010/Y4XJYC8SQ2JCRGWACAQ6WAG2D.jpg_400x400'},
                {goods_id:1,goods_name:'粘土人 咒术回战 夏油杰 高专ver.Q版可动手办',goods_price:372,goods_big_logo:'http://img.moehot.com/img/2024/05/21/0000/E5712FFRE8YF4BKKCAN40QB23.jpg_249x249'},
                {goods_id:1,goods_name:'代理版 进击的巨人 抱抱系列 怀抱玩偶 亚克力挂件',goods_price:60,goods_big_logo:'http://img.moehot.com/img/2024/06/11/0004/068MQHKSK1RJG4M3CAQ59YWRJ.jpg_400x400'},
                {goods_id:1,goods_name:'孤独摇滚! 波奇酱的运动服/Mens',goods_price:1146,goods_big_logo:'http://img.moehot.com/img/2022/11/29/0004/KJPZY7Y6TGPAC6CWB80NF3ET1.jpg_249x249'},
                {goods_id:1,goods_name:'某科学的超电磁炮T 御坂美琴 1/7标准比例完成品手办',goods_price:738,goods_big_logo:'http://img.moehot.com/img/2024/05/21/0000/2T73T18ZKP1TQJQ3CAN4ZZGWC.jpg_400x400'},
                {goods_id:1,goods_name:'原神 趴趴叠罗汉毛绒玩偶 Vol.1（盒装6个入）',goods_price:473,goods_big_logo:'http://img.moehot.com/img/2021/11/04/0005/PC2HA4M8APWBJ2WAB7RPW79DT.jpg_400x400'},
                {goods_id:1,goods_name:'jp 原神 趴趴叠叠乐毛绒玩偶挂件 Vol.3（盒装6个入）',goods_price:525,goods_big_logo:'http://img.moehot.com/img/2023/10/24/0004/8BGE31MGWW55TAD2B91PD1ZSZ.jpg_400x400'},
                {goods_id:1,goods_name:'jp 鬼灭之刃 柱训练篇 现实咖啡馆 第二话 剧本插画亚克力立牌',goods_price:159,goods_big_logo:'http://img.moehot.com/img/2024/05/22/0001/G5FPNEYQWJR48TTGCAN8BF6DB.jpg_400x400'},
                {goods_id:1,goods_name:'jp 鬼灭之刃 柱训练篇 现实咖啡馆 第一话 剧本插画亚克力立牌',goods_price:159,goods_big_logo:'http://img.moehot.com/img/2024/05/16/0005/JPQW4ECK12075PCJCANM4HGR6.jpg_400x400'},
            ],
            //其他页面的广告图片
            other_picture_list:[
                {id:1,src:'https://ts1.cn.mm.bing.net/th/id/R-C.88d85c6e8ee627e4d6094d97473d2a2f?rik=lC5ZOgKsDX9bJA&riu=http%3a%2f%2fnewssrc.onlinedown.net%2fd%2ffile%2f20160911%2f1473583271551.jpg&ehk=Rx64JE5rqskshEI%2b5fm2N6NK1yrgYvY51aZ7xmY8p2Q%3d&risl=&pid=ImgRaw&r=0'},
                {id:2,src:'https://nowre.com/wp-content/uploads/2018/10/1_NXJqARGP7W96TBdrvnXoZw.jpeg'},
                {id:3,src:'https://tse1-mm.cn.bing.net/th/id/OIP-C.LsO0fz7sa9opWfrO_kBSUwAAAA?rs=1&pid=ImgDetMain'},
            ],
            //购物车全选状态
            shopping_car_all_state:false,
            shopping_list :JSON.parse(localStorage.getItem('cart') || '[]')
        };
    },
    //方法
    mutations: {
        increment(state) {
            state.count++;
        },
    //    改变单个商品的勾选状态
        changeGoodState(state, goods) {
            const foundGood = this.state.shopping_list.find((x) => x.goods_id === goods.goods_id);
            if (foundGood) {
                foundGood.goods_state = !foundGood.goods_state;
            }
        },
    //    全选按钮，更新全部商品的勾选状态
        changeAllGoodState(state,All_state){
            state.shopping_list.forEach((x) => {
                x.goods_state = All_state;
            });
        },
    //    添加购物车的方法
        addToCart(state,goods){
            if (!state.shopping_list.some((x) => x.goods_id === goods.goods_id)) {
                state.shopping_list.push(goods);
                console.log(state.shopping_list)
            }else {
                // state.shopping_list.find((x) => x.goods_id === goods.goods_id).goods_count++;
                alert('该商品已在购物车中')
            }
        },
    //商品移除购物车
        goOutCart(state,goods){
            state.shopping_list = state.shopping_list.filter((item) => item.goods_id !== goods.goods_id);
        },
    //    更新购物车商品的数量
        updateGoodsCount(state,goods){
            state.shopping_list.find((x) => x.goods_id === goods.goods_id).goods_count = goods.goods_count
        },
    //    点击选中框移出购物车
        goOutShoppingCar(state){
            state.shopping_list = state.shopping_list.filter(item => item.goods_state === false)
        }
    },
    //异步
    actions: {
        increment(context) {
            context.commit('increment');
        },
    },
    //计算属性
    getters: {
        getCount(state) {
            return state.count;
        },
        getShoppingCarNumber(state){
            return state.shopping_list.length
        },
        getAllGoodsMoney(state){
            return state.shopping_list
                .filter(item => item.goods_state)
                .reduce((totalMoney, item) => totalMoney + item.goods_count * item.goods_price, 0)
                .toFixed(2);
        },
    //更新现在所选商品的数量
        getSelectCount(state){
            return state.shopping_list
                .filter(item => item.goods_state)
                .reduce((totalMoney) => totalMoney + 1, 0)
        }
    },
    plugins: [vuexLocalStorage]
});

export default store;
